package handler

import (
	"context"
	"fmt"
	"zg4/online-retailers/common/dao"
	"zg4/online-retailers/common/global"
	"zg4/online-retailers/common/model"
	"zg4/online-retailers/common/proto/products"
)

type Server struct {
	products.UnimplementedProductsSrvServer
}

// AddProduct 发布商品
func (s *Server) AddProduct(_ context.Context, req *products.AddProductRequest) (*products.AddProductResponse, error) {

	product := model.Products{
		Title: req.Title,
		Cover: req.Cover,
		Price: uint(req.Price),
		Stock: uint(req.Stock),
	}
	if !dao.Create(&product) {
		return nil, fmt.Errorf("商品发布失败")
	}

	return &products.AddProductResponse{}, nil
}

// ProductList 商品列表
func (s *Server) ProductList(_ context.Context, req *products.ProductListRequest) (*products.ProductListResponse, error) {
	page := req.Page
	if page <= 0 {
		page = 1
	}

	pageSize := req.Size
	switch {
	case pageSize > 100:
		pageSize = 100
	case pageSize <= 0:
		pageSize = 10
	}

	offset := (page - 1) * pageSize

	var productList []model.Products
	global.DB.Debug().Offset(int(offset)).Limit(int(pageSize)).Order("stock desc").Find(&productList)

	var lists []*products.ProductList
	for _, m := range productList {
		lists = append(lists, &products.ProductList{
			Title: m.Title,
			Cover: m.Cover,
			Price: uint64(m.Price),
			Stock: uint64(m.Stock),
		})
	}

	return &products.ProductListResponse{
		List: lists,
	}, nil
}

// GroupBuy 拼团
func (s *Server) GroupBuy(_ context.Context, req *products.GroupBuyRequest) (*products.GroupBuyResponse, error) {
	var product model.Products
	dao.QueryId(uint(req.ProductId), &product)
	if product.Id == 0 {
		return nil, fmt.Errorf("商品不存在")
	}
	if product.Stock < uint(req.Num) {
		return nil, fmt.Errorf("商品库存不足")
	}
	totalPrice := uint(req.Num) * product.Price
	buy := model.GroupBuy{
		UserId:       uint(req.UserId),
		Username:     req.Username,
		Phone:        req.Phone,
		AddressId:    uint(req.AddressId),
		ProductId:    uint(req.ProductId),
		ProductName:  product.Title,
		ProductCover: product.Cover,
		ProductPrice: product.Price,
		Num:          uint(req.Num),
		Total:        totalPrice,
	}
	if !dao.Create(&buy) {
		return nil, fmt.Errorf("发起拼团失败")
	}
	return &products.GroupBuyResponse{}, nil
}

// GroupBuyInfo 拼团详情信息
func (s *Server) GroupBuyInfo(_ context.Context, req *products.GroupBuyInfoRequest) (*products.GroupBuyInfoResponse, error) {

	var groupBuy model.GroupBuy
	dao.QueryId(uint(req.GroupById), &groupBuy)
	if groupBuy.Id == 0 {
		return nil, fmt.Errorf("该拼团信息不存在")
	}
	return &products.GroupBuyInfoResponse{
		UserId:       uint64(groupBuy.UserId),
		Username:     groupBuy.Username,
		Phone:        groupBuy.Phone,
		AddressId:    uint64(groupBuy.AddressId),
		ProductId:    uint64(groupBuy.ProductId),
		ProductName:  groupBuy.ProductName,
		ProductCover: groupBuy.ProductCover,
		ProductPrice: uint64(groupBuy.ProductPrice),
		Num:          uint64(groupBuy.Num),
		Total:        uint64(groupBuy.Total),
	}, nil
}
